<template>
  <div class="container" style="padding: 0 10px">
    <div class="flex_js p_10_0">
      <div class="c_666 fw">条件设置</div>
      <div class="flex"></div>
    </div>
    <el-table
      :data="list"
      border
      class="tc"
      :max-height="max_height"
      highlight-current-row
      v-loading="loading"
      :default-sort="{ prop: 'sort' }"
      :row-style="{
        height: height_size == 2 ? '50px' : '',
      }"
    >
      <el-table-column label="序号" type="index" width="80px"></el-table-column>
      <el-table-column label="条件名称" prop="name"></el-table-column>
      <el-table-column label="条件关系">
        <template #default="scope: any">
          <div v-for="item in dict_list_1">
            <div
              class="tl"
              v-if="
                scope.row.judgmentType == 1 &&
                scope.row.judgmentType == item.dictCode &&
                scope.row?.identifierRuleList?.length
              "
            >
              判断
            </div>
            <div
              v-if="
                scope.row.judgmentType != 1 &&
                scope.row.judgmentType == item.dictCode &&
                scope.row.identifierRuleList?.length
              "
            >
              <el-select v-model="scope.row.identifierRuleList[0].subJudgmentType">
                <span v-for="item2 in dict_list_2">
                  <el-option
                    v-if="item2.pid == item.id"
                    :value="Number(item2.dictCode)"
                    :label="item2.dictValue"
                  ></el-option>
                </span>
              </el-select>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="值">
        <template #default="scope: any">
          <div
            v-if="
              scope.row.judgmentType != 1 &&
              scope.row.type != 4 &&
              scope.row?.identifierRuleList?.length
            "
          >
            <el-input
              v-model="scope.row.identifierRuleList[0].value"
              placeholder="请输入"
            ></el-input>
          </div>
          <div
            v-if="scope.row.judgmentType == 1 && scope.row?.identifierRuleList?.length"
          >
            <el-select v-model="scope.row.identifierRuleList[0].value">
              <el-option :value="'是'" label="是"></el-option>
              <el-option :value="'否'" label="否"></el-option>
            </el-select>
          </div>
          <div
            v-if="
              scope.row.judgmentType != 1 &&
              scope.row.type == 4 &&
              scope.row?.identifierRuleList?.length
            "
          >
            <el-select
              v-model="scope.row.identifierRuleList[0].value"
              filterable
              multiple
            >
              <el-option
                v-for="item in scope.row.metadataValueList"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="160px"
        v-if="
          has_role_list[0].has_role &&
          store.state.current_enterprise_level.some((i) => {
            return i.productId == '2' && ['3', '4'].includes(i.levelId);
          })
        "
      >
        <template #default="scope: any">
          <el-button @click="copy({ item: scope.row, index: scope.$index })"
            >复制</el-button
          >
          <el-button @click="list.splice(scope.$index, 1)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div
      class="tr m_top10"
      v-if="has_role_list[0].has_role && page_data.identifierCodeId != ''"
    >
      <el-button
        type="primary"
        :loading="btn_loading"
        @click="submit"
        v-if="
          has_role_list[0].has_role &&
          store.state.current_enterprise_level.some((i) => {
            return i.productId == '2' && ['3', '4'].includes(i.levelId);
          })
        "
        >保存</el-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { dictData, check_role } from "@/utils/check_role"; // 权限校验
import { onMounted, ref, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/service/HttpRequest";
import serviceApi from "@/service/api";
import EventBus from "@/utils/EventBus";
import { useStore } from "vuex";
const props = defineProps({
  rule_type: {
    type: Number,
  },
});
const has_role_list = ref(
  props.rule_type == 1
    ? [{ path: "mouldIdentifier/post", has_role: false }]
    : props.rule_type == 2
    ? [{ path: "partsIdentifier/post", has_role: false }]
    : [{ path: "partsselfIdentifier/post", has_role: false }]
);
const store = useStore();
const height_size = ref(1);
const page_data = ref({
  current: 1,
  pageSize: 500,
  name: "",
  identifierId: "",
  identifierCodeId: "",
  templateIdList: [],
  metadataInfo: {
    isUse: 1,
  },
  isUse: 1,
});
const list = ref();
const max_height = ref();
nextTick(() => {
  max_height.value =
    window.innerHeight -
    (store.state.has_copy_mould && store.state.user_info.isAdmin ? 270 : 220);
});
const event_param = ref();

const dict_list_1 = ref();

const dict_list_2 = ref();
onMounted(() => {
  has_role_list.value.forEach((item) => {
    item.has_role = check_role(item);
  });
  EventBus.on("number_id", (e) => {
    console.log(e);
    event_param.value = e;
    page_data.value.identifierCodeId = event_param.value.id;
    page_data.value.identifierId = event_param.value.tem_id;
    page_data.value.templateIdList = event_param.value.temId_list;
    if (event_param.value.id == "") {
      list.value = [];
    } else {
      get_list();
    }
  });
  dictData("1547842801364897793").then((res) => {
    dict_list_1.value = res as any;
  }); // 字典中 判断方式 对应的值
  dictData("1547842801364897794").then((res) => {
    dict_list_2.value = res as any;
  }); // 字典中 判断类型 对应的值
});
onUnmounted(() => {
  EventBus.off("rule_id");
  EventBus.off("number_id");
  list.value = [];
});
const copy = (e) => {
  list.value.splice(e.index, 0, JSON.parse(JSON.stringify(e.item)));
};
const btn_loading = ref(false);
const submit = () => {
  let data = {
    identifierId: page_data.value.identifierId,
    identifierCodeId: page_data.value.identifierCodeId,
    ruleList: [],
  };
  list.value.forEach((item, index) => {
    item.identifierRuleList.forEach((item1, index1) => {
      if (item1.value == "是" && item.judgmentType == 1) {
        item1.subJudgmentType = "1";
      } else if (item1.value == "否" && item.judgmentType == 1) {
        item1.subJudgmentType = "2";
      }
      if (item1.subJudgmentType != "" && index1 == 0) {
        item1.sort = index + 1;
        item1.metadataId = item.id;
        item1.value = Array.isArray(item1.value) ? item1.value.join("||") : item1.value;
        data.ruleList.push(item1);
      }
    });
  });
  console.log(list.value, data);
  if (btn_loading.value) return;
  btn_loading.value = true;
  axios
    .request({ url: serviceApi.require_crud, method: "post", data: data })
    .then((res) => {
      console.log(res);
      ElMessage.success("操作成功！");
      btn_loading.value = false;
      get_list();
    })
    .catch((err) => {
      btn_loading.value = false;
      ElMessage.error(err);
    });
};
const loading = ref(false);
const get_list = () => {
  if (loading.value) return;
  loading.value = true;
  axios
    .request({
      url: serviceApi.require_list,
      method: "post",
      data: page_data.value,
    })
    .then((res) => {
      console.log(res);
      loading.value = false;
      if (res.data.content.length) {
        res.data.content.forEach((item, index) => {
          if (item.identifierRuleList.length > 1) {
            // 同一条件 多个值处理
            item.identifierRuleList.forEach((item1, index1) => {
              if (index1 > 0) {
                index += 1;
                let obj = JSON.parse(JSON.stringify(item));
                obj.identifierRuleList = [item1];
                res.data.content.splice(index, 0, obj);
              }
            });
          }
        });
      }
      // 两次循环 是因为第一次 更改了原数组的长度
      res.data.content.forEach((item) => {
        // 如果没有值  给一个默认参数 供下拉选择及输入框
        if (item.identifierRuleList.length == 0) {
          item.identifierRuleList.push({
            subJudgmentType: "",
            value: "",
          });
        } else {
          item.type == 4
            ? (item.identifierRuleList[0].value =
                item.identifierRuleList[0].value == ""
                  ? item.identifierRuleList[0].value
                  : item.identifierRuleList[0].value.split("||"))
            : "";
        }
      });
      console.log(res);
      list.value = res.data.content;
    })
    .catch((err) => {
      loading.value = false;
      ElMessage.error(err);
    });
};
</script>

<style lang="scss" scoped>
:deep(.el-input) {
  .el-input__inner {
    padding-right: 11px !important;
  }
}
</style>
